<template>
  <view class="coupon-center">
    <view class="header">
      <text class="title">领券中心</text>
    </view>
    <view class="coupon-list">
      <!-- 优惠券列表 -->
      <block v-for="coupon in couponList" :key="coupon.id">
        <view class="coupon-item">
          <view class="coupon-value">{{ coupon.type === 1 ? '满' + coupon.fullMoney + '减' + coupon.minus : coupon.discount + '折' }}</view>
          <view class="coupon-info">
            <text class="coupon-name">{{ coupon.name }}</text>
            <text class="coupon-desc">{{ coupon.details }}</text>
            <text class="coupon-expire">有效期至: {{ formatDate(coupon.endTime) }}</text>
          </view>
          <view class="coupon-get" @click="getCoupon(coupon.id)">{{ coupon.remainCount > 0 ? '立即领取' : '已领完' }}</view>
        </view>
      </block>
    </view>
  </view>
</template>

<script>
import { getCouponList, receiveCoupon } from '@/api/coupon/index'

export default {
  data() {
    return {
      couponList: []
    }
  },
  onLoad() {
    this.getCouponData()
  },
  methods: {
    getCouponData() {
      getCouponList().then(res => {
        this.couponList = res.rows || res.data || []
      }).catch(err => {
        console.error('获取优惠券列表失败:', err)
      })
    },
    getCoupon(id) {
      receiveCoupon(id).then(res => {
        uni.showToast({
          title: '领取成功',
          icon: 'success'
        })
        // 刷新列表
        this.getCouponData()
      }).catch(err => {
        uni.showToast({
          title: err.msg || '领取失败',
          icon: 'none'
        })
      })
    },
    formatDate(date) {
      // 简单的日期格式化函数
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
.coupon-center {
  padding: 20rpx;
}
.header {
  text-align: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
}
.coupon-list {
  margin-top: 20rpx;
}
.coupon-item {
  display: flex;
  padding: 20rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}
.coupon-value {
  font-size: 48rpx;
  font-weight: bold;
  color: #e64340;
  width: 180rpx;
  text-align: center;
  padding-top: 20rpx;
}
.coupon-info {
  flex: 1;
  padding: 0 20rpx;
}
.coupon-name {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}
.coupon-desc {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 10rpx;
}
.coupon-expire {
  font-size: 26rpx;
  color: #999;
}
.coupon-get {
  width: 120rpx;
  height: 60rpx;
  line-height: 60rpx;
  text-align: center;
  background-color: #e64340;
  color: #fff;
  border-radius: 30rpx;
  font-size: 28rpx;
  margin-top: 30rpx;
}
.coupon-get:disabled {
  background-color: #ccc;
}
</style>